<template>
<div class="homer">

     <van-tabs>
      <van-tab
        v-for="category in categories"
        :title="category.name"
        :key="category.id">
      </van-tab>
    </van-tabs>

    <div class="homer">
      <van-list
      class="home"
       v-model="loading"
      :finished="isEnd"
      finished-text="没有更多了"
      @load="onLoad">
     <div class="shopCard"
        v-for="item in products"
         @click="jumpToDetail(item.id)"
        :key="item.id">
   <img :src="item.image" alt="">
   <h5>{{item.title}}</h5>
   <p>￥{{item.price}}元</p>
</div>
</van-list>
</div>
</div>
</template>

<script>
import { getCategories, getHots } from '@/api/home'
export default {
  name: 'Home',
  data() {
    return {
      categories: [],
      reachBottomDistance: 100,
      products: [], // 推荐商品
      isEnd: false, // 是否所有推荐商品已查完
      nextIndex: 0, // 下一页推荐商品查询起始索引
      loading: true, // 商品列表中是否正在加载列表数据
      finished: false,
    }
  },
  async created() {
    try {
      // const result = await Promise.allSettled([
      // 同时发送两个网络请求，Promise.all() 返回一个 Promise 对象
      // 当返回的 Promise 对象状态变为 fulfilled 时，成功请求的数据
      // 会返回到解构的变量中
      // const result = await Promise.all([
      // const [obj1, obj2] = await Promise.all([
      // const [{list}, {list}] = await Promise.all([
      const [
        { list: categories },
        { list: products, isEnd, nextIndex },
      ] = await Promise.all([
        getCategories(),
        getHots(),
      ])
      // 修改 data 数据，以响应式渲染
      this.categories = categories
      this.products = products
      this.nextIndex = nextIndex
      this.isEnd = isEnd
      this.loading = false
    } catch (error) {
      console.error('有错误：', error)
    }
  },
  methods: {
    async onLoad() {
      // 异步更新数据
      const { list, nextIndex, isEnd } = await getHots(this.nextIndex)
      this.products = [
        ...this.products, // 浅拷贝，将原有 products 数组中的元素复制到新数组中
        ...list,
      ]
      this.nextIndex = nextIndex
      this.isEnd = isEnd
      this.loading = false
    },
    jumpToDetail(id) {
      this.$router.push('/detail/' + id)
    },
  },
}
</script>

<style  lang="less" scoped >
.home{
  width: 100%;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  .shopCard{
    width: 43%;
    height: 6rem;
    display: flex;
    flex-direction: column;
    border-radius: 20px;
    border: 1px solid #ccc;
    img{
      height: 250px;
      width: 100%;
    }
    h5{
      height: 0.5rem;
    text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
    }
    p{
      color: red;
    }
  }
}
</style>
